/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mabi.frontend.appbuilder;

import com.mabi.frontend.FrontEndApp;
import com.mabi.frontend.mock.MabiModuleComponent;
import com.mabi.modular.runtime.module.contributions.views.View;
import com.mabi.modular.runtime.module.contributions.zones.Zone;
import com.vaadin.terminal.ClassResource;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.Accordion;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.CustomLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Layout;
import com.vaadin.ui.SplitPanel;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.Notification;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Justo Disla
 */
public class MabiAppBuilder implements Serializable {

    private static MabiAppBuilder instance;
    private FrontEndApp frontEndApp;
    private Window appMainWindow;
    private String layoutFile = "simpleinterface";

    public static MabiAppBuilder getDefault(FrontEndApp frontEndApp) {
        if (null == instance) {
            instance = new MabiAppBuilder(frontEndApp);
        }
        return instance;
    }

    public MabiAppBuilder(FrontEndApp app) {
        frontEndApp = app;
    }

    /**
     * Builds the main layout based on the layout file provided for the application and
     * the contributions of the loaded modules.
     * Main layout should be run whenever there is a change to the module collection and at start of the application.
     * @param aThis
     * @param appMainWindow
     * @throws FileNotFoundException
     * @throws IOException 
     */
    public void refreshMainLayout(FrontEndApp aThis, Window appMainWindow) throws FileNotFoundException, IOException {
        CustomLayout cl = new CustomLayout(layoutFile);
    }

    public void buildMainAppWindow() throws FileNotFoundException, IOException {

        //Clear window
        frontEndApp.getMainWindow().removeAllComponents();

        //Builds the mainLayout
        CustomLayout mainLayout = this.buildMainLayout();

        //Create content layout zones
        Zone headerSubZone = new Zone();
        headerSubZone.setDebugId(FrontEndApp.HEADER_SUB_ZONE);
        SplitPanel eastAndContentZones = new SplitPanel();
        eastAndContentZones.setOrientation(SplitPanel.ORIENTATION_HORIZONTAL);
        VerticalLayout centerContainer = new VerticalLayout();
        Zone eastSubZone = new Zone();
        eastSubZone.setDebugId(FrontEndApp.WEST_SUB_ZONE);
        Zone contentSubZone = new Zone();
        contentSubZone.setDebugId(FrontEndApp.CENTER_SUB_ZONE);
        Zone southSubZone = new Zone();
        southSubZone.setDebugId(FrontEndApp.SOUTH_SUB_ZONE);

        //Assemble
        eastAndContentZones.addComponent(eastSubZone);
        eastAndContentZones.addComponent(contentSubZone);
        centerContainer.addComponent(eastAndContentZones);
        mainLayout.addComponent(headerSubZone, FrontEndApp.HEADER_SUB_ZONE);
        mainLayout.addComponent(centerContainer, FrontEndApp.CENTER_SUB_ZONE);
        mainLayout.addComponent(southSubZone, FrontEndApp.FOOTER_ZONE);

        //Set dimensions
//        headerSubZone.setHeight(80f, Layout.UNITS_PIXELS);
        centerContainer.setHeight(700f, Layout.UNITS_PIXELS);
        eastSubZone.setSizeFull();
        contentSubZone.setSizeFull();
        eastAndContentZones.setSplitPosition(200, Layout.UNITS_PIXELS);
        southSubZone.setHeight(70f, Layout.UNITS_PIXELS);

        //Feed test
        southSubZone.addComponent(new Label(FrontEndApp.SOUTH_SUB_ZONE));
        //eastSubZone.addComponent(new Label(FrontEndApp.EAST_SUB_ZONE));
        //contentSubZone.addComponent(new Label(FrontEndApp.CENTER_SUB_ZONE));
        headerSubZone.addComponent(new Label(FrontEndApp.HEADER_SUB_ZONE));

        //Add the west accordion
        Accordion ac = new Accordion();

        ac.addComponent(new VerticalLayout());
        ac.addComponent(new VerticalLayout());

        ac.setSizeFull();

        eastSubZone.addComponent(ac);

        frontEndApp.getMainWindow().addComponent(mainLayout);
    }

    public void startUpFramework() throws Exception {
        //doSomeTests();
    }

    private void doSomeTests() throws Exception {
        List<View> autoOpenContributionsViews = new ArrayList();

        final View v1 = new View();
        v1.setCaption("Objectivos");
        v1.setClosable(false);
        v1.addComponent(new Label("Vista Objetivos"));
        v1.setEnabled(true);
        v1.setIcon(new ClassResource("resources/book_addresses.png", frontEndApp));
        v1.setModuleName("tango");

        View v2 = new View();
        v2.setCaption("Factores");
        v2.setDescription("Esta vista muestra los factores");
        v2.setClosable(true);
        v2.setIcon(null);
        v2.addComponent(new Label("Vista de factores"));
        v2.setIcon(new ClassResource("resources/chart_pie.png", frontEndApp));
        v2.setModuleName("tango");

        View v3 = new View();
        v3.setCaption("Administracion");
        v3.setDescription("La descripción");
        v3.setIcon(new ClassResource("resources/People_011.gif", frontEndApp));
        v3.setModuleName("tango");

        autoOpenContributionsViews.add(v1);
        autoOpenContributionsViews.add(v2);
        autoOpenContributionsViews.add(v3);

        Button b = new Button("Super");

        b.addListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                View vx = new View();
                vx.setCaption("Seguridad");
                vx.setIcon(new ThemeResource("../" + frontEndApp.getTheme() + "/images/tick.png"));
                try {
                    frontEndApp.addView(vx);
                } catch (Exception ex) {
                    Logger.getLogger(MabiAppBuilder.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        v3.addComponent(b);

        Button b2 = new Button("Borrar objetivos");
        b2.addListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                try {
                    frontEndApp.removeView(v1);
                } catch (Exception ex) {
                    frontEndApp.getMainWindow().showNotification("Error removing view " + ex.getMessage(), Notification.TYPE_HUMANIZED_MESSAGE);
                }
            }
        });

        v3.addComponent(b2);

        Button bbb = new Button("Seleccionar factores");

        bbb.addListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                frontEndApp.selectView("Factores");
            }
        });

        v3.addComponent(bbb);

        for (View view : autoOpenContributionsViews) {
            view.setData(view.getCaption());
            try {
                frontEndApp.addView(view);
            } catch (Exception exception) {
                frontEndApp.getMainWindow().showNotification("Error adding view " + exception.getMessage(), Notification.TYPE_HUMANIZED_MESSAGE);
            }
        }

        Button addObjectivesButton = new Button("Agregar objetivos");

        addObjectivesButton.addListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                try {
                    frontEndApp.addView(v1);
                } catch (Exception ex) {
                    frontEndApp.getMainWindow().showNotification("Error adding this view again: " + ex.getMessage(), Notification.TYPE_HUMANIZED_MESSAGE);
                }
            }
        });

        v3.addComponent(addObjectivesButton, 0);

        //Add to west
        //VerticalLayout vl = new VerticalLayout();
        //v1.addComponent(new DateField("Get date"));
        //v1.addComponent(new CheckBox("Tango?"));

        try {
            frontEndApp.removeView(v1);
        } catch (Exception exception) {
            frontEndApp.getMainWindow().showNotification("Error removing view " + exception.getMessage(), Notification.TYPE_HUMANIZED_MESSAGE);
        }

        try {
            frontEndApp.addView(v1, FrontEndApp.WEST_SUB_ZONE);
        } catch (Exception exception) {
            frontEndApp.getMainWindow().showNotification("Error adding view " + exception.getMessage(), Notification.TYPE_HUMANIZED_MESSAGE);
        }

        View unexistentView = new View();
        unexistentView.setCaption("Ta bare");
        unexistentView.setModuleName("tango");
        try {
            frontEndApp.removeView(unexistentView);
        } catch (Exception exception) {
            frontEndApp.getMainWindow().showNotification("Error removing view " + exception.getMessage(), Notification.TYPE_HUMANIZED_MESSAGE);
        }
    }


    private CustomLayout buildMainLayout() throws FileNotFoundException, IOException {

        CustomLayout appMainLayout = new CustomLayout(layoutFile);
        
        TabSheet ts = new TabSheet();
        ts.setSizeFull();

        //refreshLayout();
        List<MabiModuleComponent> loadedModules = new ArrayList();

        loadedModules.add(new MabiModuleComponent());

        for (MabiModuleComponent mmc : loadedModules) {
            mmc.renderContributions(appMainWindow, appMainLayout, ts, frontEndApp);
        }

        //ts.addTab(new Label("Objetivos"), "Objetivos", null);
        //ts.addTab(new Label("Factores"), "Factores", null);
        //ts.addTab(new Label("Evaluación"), "Evaluación", null);
//        List<Component> autoViewComponents = Mock.getAutoViewComponents();

//        for (Component component : autoViewComponents) {
//            ts.addTab(component, component.getCaption(), null);
//        }

        //appMainLayout.addComponent(ts, "editor");
        return appMainLayout;
    }
}
